{% extends "base.html" %}

{% block title %}Online Rec. P.533-13 Propagation Prediction{% endblock %}

{% block head %}
  {{ super() }}
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css">
  <meta name="description" content="Online HF propagation prediction using the ITU Recommendation P.533-13 Propagation Prediction Application.">
{% endblock %}

{% block page_content %}
<div id="ajax-spinner" style="display:none"></div>

<!-- Static navbar -->
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Proppy</a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">P2P</a></li>
        <li><a href="{{ url_for('main.area_predict') }}">Area</a></li>
        <li><a href="{{ url_for('main.about') }}">About</a></li>
      </ul>
    </div><!--/.nav-collapse -->
  </div><!--/.container-fluid -->
</nav>


<div class="container" style="max-width: 970px;">
	<div class="page-header">
		<h1>Proppy <small>HF Circuit Prediction: Point-to-Point</small></h1>
	</div>
  <div id="flash-container"></div>
  <div class="row">
    <div class="col-sm-6">
      <div id="map-canvas"></div>
    </div>
    <div class="col-sm-6">
      <div id="plot-div"></div>
      <div id="hover-text" class="well well-sm text-center" style="display:none">
        <p>&nbsp;</p>
      </div>
    </div>
  </div>

  <div class="modal fade" id="modal-plot" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-body">
      	   <button type="button" class="close" data-dismiss="modal">
             <span aria-hidden="true">&times;</span>
             <span class="sr-only">Close</span>
           </button>
           <div id="modal-plot-canvas" ></div>
           <div id="modal-hover-text" class="well well-sm text-center">
             <span>&nbsp;</span>
           </div>
         </div>
      </div>
    </div>
  </div>

  <form class="form-horizontal" method="post" id="parameters_form" action = "{{ url_for('ajax.predict') }}" enctype="multipart/form-data">
    {{ p2p_form.csrf_token }}
    <div class="row m-t-15">
      <div class="col-sm-offset-4 col-sm-4 text-center">
        <div id="control-btn-group" class="btn-group" role="group" aria-label="...">
          <button id="do-prediction-button" type="submit" class="btn btn-primary" disabled>
            Run Prediction<span class="glyphicon glyphicon glyphicon-refresh"></span>
          </button>
          <button id="zoom-btn" type="button" class="btn btn-primary plot-zoom" title="Open Image" disabled>
            <span class="glyphicon glyphicon glyphicon-zoom-in"></span>
          </button>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-12">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">System</h3>
          </div>
          <div class="panel-body">

      <fieldset>
          <input type="hidden" name="month" />
          <input type="hidden" name="year" />

          <div class="row">
            <div class="form-group">
              <div class="col-sm-2">
                <label class="control-label">Date</label>
              </div>
              <div class="col-sm-4">
              <div class='input-group date' id='datetimepicker'>
                <input type='text' class="form-control" name="date" required />
                  <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                  </span>
              </div>
              </div>
                <div class="col-sm-2">
                  {{p2p_form.sys_plot_type.label(class="control-label")}}
                </div>
                <div class="col-sm-4">
                  {{ p2p_form.sys_plot_type(class="form-control") }}
                </div>
              </div>
          </div>

            <div class="row">
              <div class="form-group">
                <div class="col-sm-2">
                  {{p2p_form.sys_traffic.label(class="control-label")}}
                </div>
                <div class="col-sm-4">
                  {{ p2p_form.sys_traffic(class="form-control") }}
                </div>
               <div class="col-sm-2">
                 {{p2p_form.sys_pwr.label(class="control-label")}}
               </div>
               <div class="col-sm-3">
                 {{ p2p_form.sys_pwr(class="form-control", type="number", min="1", max="1000000000", step="1", value="100.0", required=true) }}
               </div>
              </div>
            </div>

            <div class="row">
              <div class="form-group">
                <div class="col-sm-2">
                  {{p2p_form.sys_mm_noise.label(class="control-label")}}
                </div>
                <div class="col-sm-4">
                  {{ p2p_form.sys_mm_noise(class="form-control") }}
                </div>
                <div class="col-sm-2">
                  <label class="control-label">Show Text</label>
                </div>
                <div class="col-sm-1">
                  <input type="checkbox" name="sys_include_text" class="form-control">
                </div>
              </div>
            </div>

     </fieldset>
   </div>
 </div>
      </div>
    </div>

    <div class="row">
    <!-- tx params -->
    <div class="col-sm-6">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title">Tx. Site
            <img src="http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png" height="16" width="16" alt="Red Balloon">
            <button id="tx-geolocation-button" type="button" class="btn btn-primary btn-xs" title="Set Tx. Site to Current Location">
              <span class="glyphicon glyphicon-map-marker" aria-hidden="true" aria-label="Geo"></span>
            </button>
          </h3>
        </div>
        <div class="panel-body">
      <fieldset>
        <div class="row">
          <div class="form-group">
            <div class="col-sm-4">
              {{p2p_form.tx_name.label(class="control-label")}}
            </div>
            <div class="col-sm-8">
              {{ p2p_form.tx_name(class="form-control", type="text") }}
            </div>
          </div>
        </div>

        <div class="row">
          <div class="form-group">
            <div class="col-sm-4">
              {{p2p_form.tx_lat_field.label(class="control-label")}}
            </div>
            <div class="col-sm-4">
              {{ p2p_form.tx_lat_field(class="form-control", id="tx_lat_field", onchange="txPositionChanged()", type="number", min="-90.0", max="90.0", step="any", required=true) }}
            </div>
          </div>
        </div>

        <div class="row">
          <div class="form-group">
            <div class="col-sm-4">
              {{p2p_form.tx_lng_field.label(class="control-label")}}
            </div>
            <div class="col-sm-4">
              {{ p2p_form.tx_lng_field(class="form-control", id="tx_lng_field", onchange="txPositionChanged()", type="number", min="-180.0", max="180.0", step="any", required=true) }}
            </div>
          </div>
        </div>

        <div class="row">
          <div class="form-group">
            <div class="col-sm-4">
              {{p2p_form.tx_gain.label(class="control-label")}}
            </div>
            <div class="col-sm-4">
              {{ p2p_form.tx_gain(class="form-control", type="number", min="0", max="20.0", step="0.01", value="2.16", required=true) }}
            </div>
          </div>
        </div>

      </fieldset>
    </div>
  </div>
    </div> <!-- end of tx params -->

    <div class="col-sm-6">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title">Rx. Site
            <img src="http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png" height="16" width="16" alt="Blue Balloon">
            <button id="rx-geolocation-button" type="button" class="btn btn-primary btn-xs" title="Set Rx. Site to Current Location">
              <span class="glyphicon glyphicon-map-marker" aria-hidden="true" aria-label="Geo"></span>
            </button>
          </h3>
        </div>
        <div class="panel-body">
      <fieldset>
        <div class="row">
          <div class="form-group">
            <div class="col-sm-4">
              {{p2p_form.rx_name.label(class="control-label")}}
            </div>
            <div class="col-sm-8">
              {{ p2p_form.rx_name(class="form-control", type="text") }}
            </div>
          </div>
        </div>

        <div class="row">
          <div class="form-group">
            <div class="col-sm-4">
              {{p2p_form.rx_lat_field.label(class="control-label")}}
            </div>
            <div class="col-sm-4">
              {{ p2p_form.rx_lat_field(class="form-control", id="rx_lat_field", onchange="rxPositionChanged()", type="number", min="-90.0", max="90.0", step="any", required=true) }}
            </div>
          </div>
        </div>

        <div class="row">
          <div class="form-group">
            <div class="col-sm-4">
              {{p2p_form.rx_lng_field.label(class="control-label")}}
            </div>
            <div class="col-sm-4">
              {{ p2p_form.rx_lng_field(class="form-control", id="rx_lng_field", onchange="rxPositionChanged()", type="number", min="-180.0", max="180.0", step="any", required=true) }}
            </div>
          </div>
        </div>

        <div class="row">
          <div class="form-group">
            <div class="col-sm-4">
              {{p2p_form.rx_gain.label(class="control-label")}}
            </div>
            <div class="col-sm-5">
              {{ p2p_form.rx_gain(class="form-control", type="number", min="0", max="20.0", step="0.01", value="2.16", required=true) }}
            </div>
          </div>
        </div>
      </fieldset>
    </div>
  </div>
    </div> <!-- end of rx params -->
  </div> <!-- end of input params row -->
  </form>
  <div id="circuit-text" style="display:none">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Input File
          <button id="copy-input-button" type="button" class="btn btn-primary btn-xs" title="Copy to Clipboard">
            <span class="glyphicon glyphicon-copy" aria-hidden="true" aria-label="Geo"></span>
          </button>
        </h3>
      </div>
      <div class="panel-body">
        <div id="input-file-text"></div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Output File
          <button id="copy-output-button" type="button" class="btn btn-primary btn-xs" title="Copy to Clipboard">
            <span class="glyphicon glyphicon-copy" aria-hidden="true" aria-label="Geo"></span>
          </button>
        </h3>
      </div>
      <div class="panel-body">
        <div id="output-file-text"></div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<!--<script src="{{ url_for('static', filename='js/bootstrap-datepicker.js') }}"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<script>
  "use strict";
  var gcPath;
  var txMarker;
  var rxMarker;
  var plotData;
  var plotLayout;

  function initMap() {
    var mapDiv = document.getElementById('map-canvas');
    var map = new google.maps.Map(mapDiv, {
      center: {lat: 0, lng: 0},
      zoom:1,
      streetViewControl: false,
      mapTypeControl: false,
      scaleControl: true,
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL
      },
      mapTypeId: 'terrain'
    });

    txMarker = new google.maps.Marker({
      map: map,
      position: {lat: 0, lng: -30},
      draggable: true,
      icon: "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png"
    });

    rxMarker = new google.maps.Marker({
      map: map,
      position: {lat: 0, lng: 30},
      draggable: true,
      icon: "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"
    });

    var geodesicOptions = {
      strokeColor: '#ff0000',
      strokeOpacity: 1.0,
      strokeWeight: 1,
      geodesic: true,
      map: map
    };

    gcPath = new google.maps.Polyline(geodesicOptions);
    /*
    google.maps.event.addDomListener(window, "resize", function() {
      console.log("resizing the map");
      var center = map.getCenter();
      google.maps.event.trigger(map, "resize");
      map.setCenter(center);c
    });
    */
    google.maps.event.addListener(txMarker, 'drag', txMapMarkerPositionChanged);
    google.maps.event.addListener(rxMarker, 'drag', rxMapMarkerPositionChanged);
    $("#tx_lat_field").val(txMarker.getPosition().lat().toFixed(4));
    $("#tx_lng_field").val(txMarker.getPosition().lng().toFixed(4));
    $("#rx_lat_field").val(rxMarker.getPosition().lat().toFixed(4));
    $("#rx_lng_field").val(rxMarker.getPosition().lng().toFixed(4));
    updateGCPath();
  }

  function showTxPosition(position) {
    if ( ($("#tx_lat_field").val() != position.coords.latitude.toFixed(4)) ||
        ($("#tx_lng_field").val() != position.coords.longitude.toFixed(4))) {
      $("#tx_lat_field").val(position.coords.latitude.toFixed(4));
      $("#tx_lng_field").val(position.coords.longitude.toFixed(4));
      txPositionChanged();
      inputHasChanged();
    }
  }

  function showRxPosition(position) {
    if ( ($("#rx_lat_field").val() != position.coords.latitude.toFixed(4)) ||
        ($("#rx_lng_field").val() != position.coords.longitude.toFixed(4))) {
      $("#rx_lat_field").val(position.coords.latitude.toFixed(4));
      $("#rx_lng_field").val(position.coords.longitude.toFixed(4));
      rxPositionChanged();
      inputHasChanged();
    }
  }

  function txMapMarkerPositionChanged(e) {
    inputHasChanged();
    $("#tx_lat_field").val(e.latLng.lat().toFixed(4));
    $("#tx_lng_field").val(e.latLng.lng().toFixed(4));
    updateGCPath();
  }

  function rxMapMarkerPositionChanged(e) {
    inputHasChanged();
    $("#rx_lat_field").val(e.latLng.lat().toFixed(4));
    $("#rx_lng_field").val(e.latLng.lng().toFixed(4));
    updateGCPath();
  }

  function txPositionChanged() {
    txMarker.setPosition(new google.maps.LatLng($('#tx_lat_field').val(), $('#tx_lng_field').val()));
    updateGCPath();
  }

  function rxPositionChanged() {
    rxMarker.setPosition(new google.maps.LatLng($('#rx_lat_field').val(), $('#rx_lng_field').val()));
    updateGCPath();
  }

  function updateGCPath() {
    var txPosition = new google.maps.LatLng($('#tx_lat_field').val(), $('#tx_lng_field').val());
    var rxPosition = new google.maps.LatLng($('#rx_lat_field').val(), $('#rx_lng_field').val());
    gcPath.setPath([txPosition, rxPosition]);
  }

  function inputHasChanged() {
    $('#do-prediction-button').prop('disabled', false);
  }

  </script>
  <script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>

  <script>

  function pad (str, max) {
    str = str.toString();
    return str.length < max ? pad("0" + str, max) : str;
  }

  $(function () {
    var dateNow = new Date();
    $('#datetimepicker').datetimepicker({
      viewMode : 'months',
      format: 'MMM YYYY',
      minDate : moment("{{min_year}} {{min_month}}", "YYYY MM"),
      maxDate : moment("{{max_year}} {{max_month}}", "YYYY MM"),
      defaultDate:dateNow
    });
  });

  $(document)
  .ajaxStart(function(){
      $("#ajax-spinner").show();
  })
  .ajaxStop(function(){
      $("#ajax-spinner").hide();
  });

  $("#parameters_form").submit( function ( e ) {        //console.log(plotData['p']['name']);

    do_prediction(e.target);
    e.preventDefault();
  });

  function setHoverWindowVisible(visible) {
    if (window.innerWidth > 768) {
      console.log("we're on a big screen");
      if (visible) {
        console.log('going visible');
        $('#hover-text').show();
      } else {
        console.log('hiding');
        $('#hover-text').hide();
      }
    }
  }

  function bindHoverWindowEvents(plotDiv, hoverPanel) {
    document.getElementById(plotDiv).on('plotly_hover', function(data){
      var mesh = data.points[0];
      var muf = data.points[1];
      var hText;
      if (plotData['p']['name'] == 'BCR') {
        hText = "<span>"+pad(mesh.x,2)+":00UTC "+mesh.y+"MHz BCR: "+mesh.z+"% MUF: "+muf.y+"MHz</span>"
      } else if (plotData['p']['name'] == 'SNR') {
        hText = "<span>"+pad(mesh.x,2)+":00UTC "+mesh.y+"MHz SNR: "+mesh.z+"dB MUF: "+muf.y+"MHz</span>"
      } else if (plotData['p']['name'] == 'E'){
        hText = "<span>"+pad(mesh.x,2)+":00UTC "+mesh.y+"MHz E: "+mesh.z+"dB(1&#181;/Vm) MUF: "+muf.y+"MHz</span>"
      } else {
        hText = "<span>&nbsp</span>";
      }
      $(hoverPanel).html(hText);
    });

    document.getElementById(plotDiv).on('plotly_unhover', function(data){
      $(hoverPanel).html('<span>&nbsp</span>');
    });
  }

  function do_prediction(form) {
  	var form_obj = form;
    var dt = $("#datetimepicker").data("DateTimePicker").date();
    $("input[name='month']").replaceWith(
      $('<input>').attr({
        type: 'hidden',
        name: 'month',
        value: dt.format("M")
      })
    );
    $("input[name='year']").replaceWith(
      $('<input>').attr({
        type: 'hidden',
        name: 'year',
        value: dt.format("YYYY")
      })
    );
    var form_url = $(form_obj).attr("action");
  	var form_data = new FormData(form);
  	$.ajax( {
  		url: form_url,
  		type: 'POST',
  		data: form_data,
      dataType: "json",
  		mimeType: "multipart/form-data",
  		processData: false,
  		contentType: false,
  		success: function(result) {

      //console.log(result);
      result['p']['hoverinfo']='none';
      result['m']['hoverinfo']='none';

      if (window.innerWidth >= 768) {
        var titlefont = {
          size: 14,
          family: 'Arial, sans-serif'
        };
        result['p']['colorbar']['tickmode'] = 'array';
        result['p']['colorbar']['titleside'] = 'right';
        result['p']['colorbar']['titlefont'] = titlefont;
        result['p']['colorbar']['thickness'] = 12;
        result['p']['colorbar']['xpad'] = 3;
      } else {
        result['p']['colorbar'] = {
          tickmode:'array',
          thickness:6,
          xpad:3
        };
      }
      {% if colorscale == None %}
        result['p']['colorscale'] = 'Jet';
      {% else %}
        result['p']['colorscale'] = {{colorscale | safe}};
      {% endif %}
      //console.log(result['p']['colorbar']);
      var layout = {
        xaxis: {
          title: 'Time (UTC)',
          range: [0, 24],
          tick0: 0,
          dtick: 2,
          titlefont: {
            family: 'Arial, sans-serif',
            size: 14,
            color: '#7f7f7f'
          },
        },
        yaxis: {
          title: 'Frequency / MHz',
          range: [2, 30],
          titlefont: {
            family: 'Arial, sans-serif',
            size: 14,
            color: '#7f7f7f'
          }
        },
        margin: {
          l: 40,
          r: 20,
          b: 50,
          t: 50,
          pad: 4
        },
      };
      plotData = result;
      plotLayout = layout;
      $('#flash-container').empty();
      Plotly.newPlot('plot-div', [result['p'], result['m']], layout);
      bindHoverWindowEvents('plot-div', '#hover-text');

      if(result.hasOwnProperty('textIn') && result.hasOwnProperty('textOut')) {
        var pre = document.createElement('pre');
        var text = document.createTextNode( result['textIn'] );
        pre.appendChild(text);
        $('#input-file-text').html(pre);
        //$('#input-file-text').html('<pre>'+result['textIn']+'</pre>');
        pre = document.createElement('pre');
        text = document.createTextNode( result['textOut'] );
        pre.appendChild(text);
        $('#output-file-text').html(pre);
        //$('#output-file-text').html('<pre>'+result['textOut']+'</pre>');
        $('#circuit-text').show();
      } else {
        $('#circuit-text').hide();
        $('#input-file-text').empty();
        $('#output-file-text').empty();
      }
      $('#zoom-btn').prop('disabled', false);
      //$('#hover-text').show();
      setHoverWindowVisible(true);
      $('#map-canvas').css('margin-top', '50px');
      $('#do-prediction-button').prop('disabled', true);
    },
  	error: function(result) {
  			// Handle errors here
  			//console.log('ERRORS: ' + JSON.stringify(result));
        var message = "";
        if (result.hasOwnProperty('responseJSON')) {
          message = result['responseJSON']['statusText']
        } else if (result.hasOwnProperty('statusText')) {
          message = result['statusText'];
        } else {
          message = "An undefined error has occured.";
        }
        $('#flash-container').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');
        //$('#map-canvas').empty();
        $('#plot-div').empty();
        $('#zoom-btn').prop('disabled', true);
        setHoverWindowVisible(false);
        $('#circuit-text').hide();
        $('#input-file-text').empty();
        $('#output-file-text').empty();

        $('#do-prediction-button').prop('disabled', false);
  		}
  	});
  }

  window.onresize = function() {
    var update = {
      width: $('#plot-div').width()
    }
    Plotly.relayout('plot-div', update)
  };


  function copyToClipboard(textArea) {
    var range = document.createRange();
    var msg;
    range.selectNodeContents(textArea.get(0));
    selection = window.getSelection ();
    selection.removeAllRanges ();
    selection.addRange (range);
    // Lets copy.
    try {
      success = document.execCommand ("copy", false, null);
      msg = 'Text has been copied to the system clipboard';
    } catch (e) {
      msg = 'Failed to copy text to the system clipboard';
    }
    document.getSelection().removeAllRanges();
    alert(msg);
  }

</script>

<script>


$(document).ready(function(){
    $('#parameters_form').on('change', function(e) {
      inputHasChanged();
    });


    $("#datetimepicker").on("dp.change", function (e) {
      inputHasChanged();
    });


    $('#tx-geolocation-button').on('click', function (e) {
      navigator.geolocation.getCurrentPosition(showTxPosition);
    });


    $('#rx-geolocation-button').on('click', function (e) {
      navigator.geolocation.getCurrentPosition(showRxPosition);
    });


    $('#copy-input-button').on('click', function (e) {
      copyToClipboard($("#input-file-text"));
    });


    $('#copy-output-button').on('click', function (e) {
      copyToClipboard($("#output-file-text"));
    });


    $('#do-prediction-button').prop('disabled', false);


    $('#zoom-btn').on('click', function() {
			$('#modal-plot').modal('show');
      $('#plot-div').empty();
      plotLayout['width'] = $(window).width() * 0.8;
      Plotly.newPlot('modal-plot-canvas', [plotData['p'], plotData['m']], plotLayout);
      bindHoverWindowEvents('modal-plot-canvas', '#modal-hover-text')
		});


    $('#modal-plot').on('hidden.bs.modal', function (e) {
      plotLayout['width'] = $('#plot-div').width();
      Plotly.newPlot('plot-div', [plotData['p'], plotData['m']], plotLayout);
      bindHoverWindowEvents('plot-div', '#hover-text')
    });

});
</script>
{% endblock %}
